/*
 * Copyright (c) 2024, Qi Yaolong.
 * dragon@hbu.edu.cn
 * HeBei University, China.
 * 
 * 简体中文
 * 保留所有权利。依据GPL 2.0（以下简称"本许可"）进行许可。除非符合（遵守）本许可及以下条款，否则
 * 您不得使用此文件：
 * 
 * 禁止任何未经授权的个人或组织以任何形式将本程序及其附属资料、创新、创意、架构设计、算法、衍生作品
 * 等用于任何商业目的、盈利活动、各类竞赛(比赛)、直播教学、录播教学、线下课程、书籍编写、教材编写、
 * 会议、培训、公益活动、项目课题、毕业设计、毕业论文、学术论文等。
 * 
 * 本程序由版权持有人和贡献人“按原样”提供，不提供任何明示或暗示担保，包括但不局限于对适销性和特定
 * 用途适合性的暗示担保。在任何情况下，版权持有人或贡献人对因使用本程序而导致的任何直接、间接、附带、
 * 特殊、典型或后果性损害（包括但不限于购买替代商品或服务；使用损失、数据丢失或利润损失；业务中断）
 * 不承担任何责任，无论其如何产生，也不论其责任理论为何，无论是合同、严格责任还是侵权（包括疏忽或
 * 其他），即使已告知此类损害的可能性。
 * 
 * English
 * All rights reserved. Licensed under the GPL 2.0 (the "License"). You may NOT 
 * use this file except in compliance with the License and the following terms:
 * 
 * IT IS PROHIBITED FOR ANY UNAUTHORIZED PERSON OR ENTITY TO USE THIS PROGRAM AND 
 * ITS ANCILLARY DATA, INNOVATIONS, CONCEPTS, ARCHITECTURE DESIGN, ALGORITHMS, 
 * DERIVED WORKS, ETC., IN ANY FORM FOR COMMERCIAL PURPOSES, PROFIT-MAKING 
 * ACTIVITIES, VARIOUS COMPETITIONS (CONTESTS), LIVE TEACHING, PRE-RECORDED 
 * LESSONS, OFFLINE COURSES, BOOK WRITING, CONFERENCES, TRAININGS, PUBLIC WELFARE 
 * ACTIVITIES, PROJECTS, TOPICS, GRADUATION DESIGNS, DISSERTATIONS, THESES, AND 
 * OTHER APPLICATIONS.
 * 
 * THIS PROGRAM IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS PROGRAM, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "stdlib.h"
#include "ohos_init.h" // 用于初始化服务(services)和功能(features)
#include "cmsis_os2.h" // CMSIS-RTOS API V2

// lwIP：A Lightweight TCPIP stack
// 瑞典计算机科学院(SICS)的Adam Dunkels开发的一个小型(轻量)开源的TCP/IP协议栈
// 实现的重点是在保持TCP协议主要功能的基础上减少对RAM的占用
// 仅占用几十KB RAM空间，40KB ROM空间，非常适合在嵌入式系统中使用
//
// lwIP TCP/IP协议栈：网络接口API
// netifapi：Network Interfaces API
#include "lwip/netifapi.h"

#include "soc_osal.h"
#include "errcode.h"
#include "wifi_hotspot.h"
#include "wifi_hotspot_config.h"
#include "wifi_linked_info.h"
#include "wifi_device_config.h"

#define WIFI_IFNAME_MAX_SIZE 16

errcode_t StartHotspot(char *ssid, char *pre_shared_key, wifi_security_enum security_type, uint8_t channel_num)
{
    /* WiFi SoftAP 网络设备名，SDK默认是ap0, 以实际名称为准 */
    char ifname[WIFI_IFNAME_MAX_SIZE] = "ap0";

    // 设置IP地址、子网掩码、网关地址
    ip4_addr_t st_ipaddr = {0};
    ip4_addr_t st_netmask = {0};
    ip4_addr_t st_gw = {0};
    IP4_ADDR(&st_ipaddr, 192, 168, 63, 1);   /* IP地址设置：192.168.63.1 */
    IP4_ADDR(&st_netmask, 255, 255, 255, 0); /* 子网掩码设置：255.255.255.0 */
    IP4_ADDR(&st_gw, 192, 168, 63, 2);       /* 网关地址设置：192.168.63.2 */

    // Hotspot的配置
    softap_config_stru hapd_conf = {0};
    memcpy_s(hapd_conf.ssid, sizeof(hapd_conf.ssid), ssid, strlen(ssid));                   /* SSID */
    memcpy_s(hapd_conf.pre_shared_key, WIFI_MAX_KEY_LEN, pre_shared_key, WIFI_MAX_KEY_LEN); /* 密码 */
    hapd_conf.security_type = security_type;                                                // WiFi安全类型
    hapd_conf.channel_num = channel_num;                                                    /* 工作信道 */

    // 启动Hotspot
    osal_printk("Hotspot try enable.\r\n");
    while (wifi_softap_enable(&hapd_conf) != ERRCODE_SUCC)
    {
        osal_printk("Hotspot enable fail, retry...\r\n");
        osal_msleep(100);
    }

    /* 配置DHCP服务器 */
    struct netif *netif_p = NULL;
    netif_p = netif_find(ifname);
    if (netif_p == NULL)
    {
        osal_printk("find netif fail.\r\n", ifname);
        wifi_softap_disable();
        return ERRCODE_FAIL;
    }
    if (netifapi_netif_set_addr(netif_p, &st_ipaddr, &st_netmask, &st_gw) != ERR_OK)
    {
        osal_printk("set addr fail.\r\n");
        wifi_softap_disable();
        return ERRCODE_FAIL;
    }
    if (netifapi_dhcps_start(netif_p, NULL, 0) != ERR_OK)
    {
        osal_printk("dhcps start fail.\r\n");
        wifi_softap_disable();
        return ERRCODE_FAIL;
    }

    osal_printk("Hotspot start success.\r\n");
    return ERRCODE_SUCC;
}
